package gamejam.platformer;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

public class MovingPlatform extends Tile {
	
	private int left;
	private int right;
	private boolean movingRight = true;
	private int span;
	private int actualWidth;
	private int tick = 0;
	private Player player = null;
	
	public MovingPlatform(Image img, int x, int y, int left, int right, int span) {
		this(img, x, y, img.getWidth(null) * span, img.getHeight(null), left, right, span);
	}
	
	public MovingPlatform(Image img, int x, int y, int width, int height, int left, int right, int span) {
		super(img, x, y, width, height);
		this.left = left;
		this.right = right;
		this.span = span;
		this.actualWidth = width / span;
	}
	
	public void attach(Player player) {
		this.player = player;
	}
	
	public void dettach() {
		this.player = null;
	}
	
	public void draw(Graphics g, int xOffset, int yOffset) {
		for (int i=0; i<span; i++)
			g.drawImage(getImage(), getX() - xOffset + actualWidth * i, getY() - yOffset, actualWidth, getHeight(), null);
	}
	
	public void drawBoundingBox(Graphics g, int xOffset, int yOffset) {
		Color c = g.getColor();
		g.setColor(Color.CYAN);
		for (int i=0; i<span; i++)
			g.drawRect(getX() - xOffset + actualWidth * i, getY() - yOffset, actualWidth - 1, getHeight() - 1);
		g.setColor(c);
	}
	
	public void tick() {
		tick++;
		if (tick == 5) {
			tick = 0;
			if (movingRight) {
				int x = Math.min(getX() + getWidth() + 1, right) - getWidth();
				if (x == right - getWidth())
					movingRight = false;
				if (player != null && player.canMoveRight(1))
					player.setX(player.getX() + 1);
				setX(x);
			} else {
				int x = Math.max(getX() - 1, left);
				if (x == left)
					movingRight = true;
				if (player != null && player.canMoveLeft(1))
					player.setX(player.getX() - 1);
				setX(x);
			}
		}
	}
	
	public String toString() {
		return String.format("%s[x=%s, y=%s, w=%s, h=%s, l=%s, r=%s, s=%s, a=%s]", this.getClass().getCanonicalName(),
				getX(), getY(), getWidth(), getHeight(), left, right, span, actualWidth);
	}
}
